const Router = require("@koa/router");
const router = new Router();
const startConnect = require("../db");
const {
  verifyToken,
  encryptPwd,
  decodePwd
} = require("../core/util");

//添加阅览室
router.post("/add_reading_room", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 1) {
    const {
      name,
      open,
      open_time,
      located,
      seats,
      total
    } = ctx.request.body;
    console.log("添加阅览室", ctx.request.body);
    await startConnect(
      `select id from reading_rooms where name='${name}'`
    ).then(async (res) => {
      if (res[0]) {
        ctx.body = {
          tag: false,
          msg: "该阅览室名称已存在",
        };
      } else {
        const sql = `insert into reading_rooms(name,located,open,open_time,seats,total) values('${name}','${located}',${open},'${open_time}','${JSON.stringify(
          seats
        )}','${total}') `;
        await startConnect(sql).then((res) => {
          ctx.body = {
            tag: res.affectedRows,
          };
        });
      }
    });
  } else {
    ctx.body = 404;
  }
});

//修改阅览室
router.post("/change_reading_room", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  console.log("修改阅览室", isValid);
  if (isValid && isValid.scope === 1) {
    const {
      open,
      open_time
    } = ctx.request.body;
    const sql = `update reading_rooms set open =${open},open_time  = '${open_time}'`;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//删除阅览室
router.post("/del_reading_room", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  console.log("删除阅览室", isValid);
  if (isValid && isValid.scope === 1) {
    const {
      id
    } = ctx.request.body;
    console.log("id", ctx);
    const sql = `delete from reading_rooms where id= '${id}'`;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//批量添加用户
router.post("/batch_add_user", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  console.log("批量添加用户", isValid);
  if (isValid && isValid.scope === 1) {
    console.log("USERS", ctx.request.body);
    const {
      users
    } = ctx.request.body;
    let insertValues = "",
      checkValues = "(";
    users.forEach((v, idx) => {
      insertValues += `('${v}','${encryptPwd("user" + v)}','男'),`;
      checkValues += `'${v}',`;
    });
    insertValues = insertValues.slice(0, -1);
    checkValues = checkValues.slice(0, -1);
    checkValues += ")";
    const sql = `select id from user where username in ${checkValues}`;
    console.log("check", sql);
    await startConnect(sql).then(async (res) => {
      if (!res[0]) {
        const sql = `insert into user (username,password,sex) values ${insertValues}`;
        console.log(sql);
        await startConnect(sql).then((res) => {
          ctx.body = {
            tag: res.affectedRows,
          };
        });
      } else {
        ctx.body = {
          tag: false,
          msg: "名单含有已注册用户名",
        };
      }
    });
  } else {
    ctx.body = 404;
  }
});

//添加单个用户
router.post("/add_user", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  console.log("添加单个用户", isValid);
  if (isValid && isValid.scope === 1) {
    console.log("USERS", ctx.request.body);
    const {
      username,
      sex,
      phone,
      email,
      state
    } = ctx.request.body;
    const sql1 = `select id from user where username = '${username}'`;
    await startConnect(sql1).then(async (res) => {
      if (!res[0]) {
        const sql = `insert into user (username,sex,phone,email,state,password) values('${username}','${sex}','${phone}','${email}','${state}','${encryptPwd("user" + username)}')`;
        console.log(sql);
        await startConnect(sql).then((res) => {
          ctx.body = {
            tag: res.affectedRows,
          };
        });
      } else {
        ctx.body = {
          tag: false,
          msg: "名单含有已注册用户名",
        };
      }
    });
  } else {
    ctx.body = 404;
  }
});

//删除该用户
router.post("/del_user", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  console.log("删除用户", isValid);
  if (isValid && isValid.scope === 1) {
    const {
      id
    } = ctx.request.body;
    const sql = `delete from user where id= '${id}'`;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//获取所有用户信息
router.get("/users_info", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 1) {
    const sql = `select id,username,password,sex,phone,email,state from user where id != '1'`;
    await startConnect(sql).then((res) => {
      res.forEach((v, index) => {
        res[index].state = v.state == 1 ? true : false;
        res[index].password = decodePwd(res[index].password);
      });
      ctx.body = {
        tag: res.length ? true : false,
        data: res,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//更新用户信息
router.post("/update_user_info", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid) {
    const {
      id,
      username,
      sex,
      phone,
      email,
      password
    } = ctx.request.body;
    const state = ctx.request.body.state ? 1 : 0;

    //更改时间
    const checkEmail = `select id from user where email ='${email}' and id !='${id}' and email != null`;
    const checkPhone = `select id from user where phone ='${phone}' and id !='${id}' and phone != null`;
    const checkUsername = `select id from user where username ='${username}' and id !='${id}'`;
    const sql = `update user set username = '${username}',sex = '${sex}',phone = '${phone}',email = '${email}',state = '${state}',password = '${encryptPwd(
      password
    )}'where id = '${id}'`;

    await Promise.all([
      startConnect(checkEmail),
      startConnect(checkPhone),
      startConnect(checkUsername),
    ]).then(async (res) => {
      let invalidFiled = res[0][0] ? "邮箱" : "";
      invalidFiled += res[1][0] ? (invalidFiled ? "、手机号" : "手机号") : "";
      invalidFiled += res[2][0] ? (invalidFiled ? "、用户名" : "用户名") : "";
      if (invalidFiled.length) {
        ctx.body = {
          tag: false,
          msg: `${invalidFiled}与其他用户冲突`,
        };
      } else {
        await startConnect(sql).then((res, e) => {
          ctx.body = {
            tag: res.affectedRows,
          };
        });
      }
    });
  } else {
    ctx.body = 404;
  }
});

//更新用户状态
router.post("/update_user_state", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 1) {
    const {
      id,
      state
    } = ctx.request.body;
    console.log(ctx.request.body, "body");
    const sql = `update user set state = ${state} where id = '${id}'`;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//更新阅览室状态
router.post("/update_room_state", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 1) {
    const {
      id,
      open,
      open_time
    } = ctx.request.body;
    console.log(ctx.request.body, "更新阅览室状态");
    const sql = `update reading_rooms set open = ${open},open_time = '${JSON.stringify(open_time)}' where id = '${id}' `;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//获取所有意见
router.get("/feedback", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 1) {
    const sql = `select u.username,f.id,f.rate,f.user_id,f.created_date,f.feedback_content,f.reply_date,f.reply_content  from feedback as f,user as u where u.id = f.user_id`;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: true,
        data: res,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//回复意见
router.post("/reply_feedback", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 1) {
    const {
      id,
      content
    } = ctx.request.body;
    const sql = `update feedback set reply_content ='${content}', reply_date = CURRENT_TIMESTAMP where id = '${id}'`;
    console.log("sql", sql);
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//发布公告
router.post("/post_notice", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 1) {
    const {
      title,
      content
    } = ctx.request.body;
    console.log(ctx.request.body, "发布公告");
    const sql = `insert into notice(title,content) values('${title}','${content}')  `;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//获取公告
router.get("/get_notice", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid) {
    const sql = `select * from notice`;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: true,
        data: res,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//删除公告
router.post("/del_notice", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  if (isValid && isValid.scope === 1) {
    const {
      id
    } = ctx.request.body;
    console.log(ctx.request.body, "删除公告");
    const sql = `delete from notice where id = '${id}'`;
    await startConnect(sql).then((res) => {
      ctx.body = {
        tag: res.affectedRows,
      };
    });
  } else {
    ctx.body = 404;
  }
});

module.exports = router;